package com.itheima.request.param;

import com.itheima.request.domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/*
* 反射封装
* */
@WebServlet("/demo6")
public class ServletDemo6 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Map<String, String[]> map = req.getParameterMap();
        User user = new User();
        Set<String> keys = map.keySet();
        try {
            for (String key : keys) {
                Field field = user.getClass().getDeclaredField(key);
                field.setAccessible(true);
                String[] values = map.get(key);
                if (values.length==1){
                    field.set(user,values[0]);
                }else if (values.length>1){
                    field.set(user,values);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
